import os
import json
import hashlib
from typing import Any, Dict, Optional
from pathlib import Path
import time

class CacheManager:
    def __init__(self, cache_dir: str = "./temp/cache"):
        self.cache_dir = Path(cache_dir)
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        self.memory_cache: Dict[str, Any] = {}
        self.cache_ttl = 3600  # 缓存过期时间（秒）

    def _get_cache_key(self, key: str) -> str:
        """生成缓存键"""
        return hashlib.md5(key.encode()).hexdigest()

    def _get_cache_path(self, key: str) -> Path:
        """获取缓存文件路径"""
        return self.cache_dir / f"{self._get_cache_key(key)}.json"

    def get(self, key: str) -> Optional[Any]:
        """获取缓存值"""
        # 首先检查内存缓存
        if key in self.memory_cache:
            cache_data = self.memory_cache[key]
            if time.time() - cache_data['timestamp'] < self.cache_ttl:
                return cache_data['value']
            else:
                del self.memory_cache[key]

        # 检查文件缓存
        cache_path = self._get_cache_path(key)
        if cache_path.exists():
            try:
                with open(cache_path, 'r', encoding='utf-8') as f:
                    cache_data = json.load(f)
                    if time.time() - cache_data['timestamp'] < self.cache_ttl:
                        # 更新内存缓存
                        self.memory_cache[key] = cache_data
                        return cache_data['value']
                    else:
                        cache_path.unlink()
            except Exception:
                if cache_path.exists():
                    cache_path.unlink()
        return None

    def set(self, key: str, value: Any) -> None:
        """设置缓存值"""
        cache_data = {
            'value': value,
            'timestamp': time.time()
        }
        # 更新内存缓存
        self.memory_cache[key] = cache_data
        # 更新文件缓存
        cache_path = self._get_cache_path(key)
        try:
            with open(cache_path, 'w', encoding='utf-8') as f:
                json.dump(cache_data, f)
        except Exception:
            if cache_path.exists():
                cache_path.unlink()

    def clear(self) -> None:
        """清除所有缓存"""
        self.memory_cache.clear()
        for cache_file in self.cache_dir.glob("*.json"):
            try:
                cache_file.unlink()
            except Exception:
                pass

    def clear_expired(self) -> None:
        """清除过期缓存"""
        current_time = time.time()
        # 清除内存缓存
        expired_keys = [
            key for key, data in self.memory_cache.items()
            if current_time - data['timestamp'] >= self.cache_ttl
        ]
        for key in expired_keys:
            del self.memory_cache[key]

        # 清除文件缓存
        for cache_file in self.cache_dir.glob("*.json"):
            try:
                with open(cache_file, 'r', encoding='utf-8') as f:
                    cache_data = json.load(f)
                    if current_time - cache_data['timestamp'] >= self.cache_ttl:
                        cache_file.unlink()
            except Exception:
                if cache_file.exists():
                    cache_file.unlink() 